/**
 * author:Administrator
 * date:2016/3/19
 * desc: 对 order 使用 优惠券
 * -> 源事件 CouponLog: CouponLogUsed
 * ->on couponLogUsed => Order: 修改自己的状态( finish ),如果失败, pub event: attchCouponFail
 * ->on attchCouponFail => CouponLog:修改自己的状态
 */

'use strict';

let Saga = require('../../lib/Saga.js');
let events = require('./domainEvent.js');

let debug = console.log.bind(console);

class CouponUseSaga extends Saga {
  constructor(couponLog, order) {
    super();
    debug(this.constructor.name + ' set up...');
    super.subscribe(events.ENUM_EVENT.couponLogUsed);
    super.subscribe(events.ENUM_EVENT.attchCouponFail);

    this.couponLog = couponLog;
    this.order = order;
  }

  * start() {
    yield this.couponLog.useSelf(this.order, this.sagaId);
  }

  * couponLogUsed(event) {
    debug('handle event ', event.type);
    // order 状态变化
    let order = event.data.order;
    let couponLog = event.data.couponLog;
    yield order.attachCoupon(couponLog, this.sagaId);

    this._end(couponLog);
  }

  * attchCouponFail(event) {
    debug('handle event ', event.type);
    // couponLog 状态变化
    let couponLog = event.data;
    yield couponLog.unUseSelf(this.sagaId);

    this._end(null);
  }

}

module.exports = CouponUseSaga;